package com.fengwk.support.proxy.http;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import com.fengwk.support.proxy.http.annotation.HttpClient;
import com.fengwk.support.util.JsonUtils;
import com.fengwk.support.util.ResultUtils;
import com.fengwk.support.util.TypeUtils;

public class DecodeImpl implements Decode {

	@Override
	public Object decode(HttpClient httpClient, Response response, Type type) {
		String result = response.getResponse();
		if (result != null) {
			if(httpClient.decodeJsonMap()) {
				// JsonMap
				return ResultUtils.decodeJsonMapData(result, type);
			}
			Class<?> typeClass = null;
			if (type.getClass() == Class.class) {
				typeClass = (Class<?>) type;
			} else {
				typeClass = (Class<?>) ((ParameterizedType) type).getRawType();
			}
			if (typeClass == String.class) {
				// String
				return result;
			}
			if (typeClass != null && TypeUtils.isCollection(typeClass)) {
				// Collection
				Type[] ts = ((ParameterizedType) type).getActualTypeArguments();
				if (ts != null && ts.length > 0) {
					return JsonUtils.fromJsonList(result, typeClass);
				}
			} else {
				// Obj
				return JsonUtils.fromJson(result, typeClass);
			}
		}
		return null;
	}

}